﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DiscoveryLogic.Analytics.DataObjects;

namespace DiscoveryLogic.Analytics.Modules.Entities
{
    /// <summary>
    /// Interaction logic for OrgListView.xaml
    /// </summary>
    public partial class OrgListView : UserControl
    {
        public delegate void OnOrgSelected(ExternalOrgDO org);

        public event OnOrgSelected OrgSelected;

        private OrgListPresenter _Presenter;

        public OrgListView()
        {
            InitializeComponent();
        }

        public OrgListView(OrgListPresenter presneter)
			: this()
		{
			_Presenter = presneter;
			_Presenter.View = this;
		}

        public List<ExternalOrgDO> Orgs
        {
            get { return this.DataContext as List<ExternalOrgDO>; }
            set
            {
                this.DataContext = value;
                if (value == null || value.Count == 0)
                {
                    this.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    this.Visibility = System.Windows.Visibility.Visible;
                }
            }
        }

        public void SubscribeEventHandler(ExternalOrgDO org)
        {
            this._Presenter.RegisterOrgSelectionChangedEventHandler(org);
        }

        private void lvOrgs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 1)
            {
                ExternalOrgDO org = e.AddedItems[0] as ExternalOrgDO;
                if (this.OrgSelected != null)
                    this.OrgSelected(org);
            }
        }

        public void SelectOrg(ExternalOrgDO org)
        {
            if (this.Orgs != null && org != null)
            {
                for (int i = 0; i < this.Orgs.Count; i++)
                {
                    if (this.Orgs[i].ExternalOrgID == org.ExternalOrgID)
                    {
                        this.lvOrgs.SelectedIndex = i;
                        break;
                    }
                }
            }
        }
    }
}
